// pages/index/index.js
var app = getApp();
var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');   
var qqmapsdk = new QQMapWX({
  key: 'BYXBZ-763KX-YTT4S-7SEOC-N5I23-I5BAE'//申请的开发者秘钥key
});

var timer = null;

var var_header = {
  'content-type': 'application/x-www-form-urlencoded',
  'cookie': "openid=" + app.globalData.openid
};

var try_times = 0;

let reInterval = 5 * 1000;
let retimes = 3;

Page({
  /**
   * 页面的初始数据
   */
  data: { 
    is_load_center_scale:false,
    detail_is_show:false,
    show_coverview_list: false, 
    current_info: '', 
    coverview_dev_list: [
    //  { 
    //   name: 'ceshi3333',
    //   id: 8,
    //   hidden: true,
    //   images: '/images/group.png',
    //   down: '/images/icon_down2x.png',
    //   points: [
    //     {
    //       devNo: '868221047652659',
    //       devName: 'ceshi123'
    //     }
    //   ]
    // }
    ], 
  
    latitude: '',
    longitude: '',
    default_latitude:'',
    default_longitude:'',   
    mapCtx:'',
    scale:16,
    ws:'',
    wxst:'',
    dev_list_detail:[
      /**测试数据 需要删除 */
      // {
      //   secondTurnOffTime: '12:00:00',
      //   devNo: '868221047652659',
      //   latitude: '32.409080',
      //   type:1,
      //   firstTurnOnTime: '12:30:00',
      //   devCurrentTime: '11:30:30',
      //   longitude:'119.420090' ,
      //   firstOrSumElec: '100',  //第一路电流或者总电流 单位毫安
      //   secondTurnOnTime: '10:00:00',
      //   auto: true,
      //   onLine: true,
      //   secondElec:'100', //第二路电流（预留）
      //   firstSwitch: true,  //第一路开关
      //   firstTurnOffTime: '13:30:00',
      //   secondSwitch: false,  //第二路开关
      //   description: 'ceshi_del'
      // }      
    ],
    markers: [
       /**测试数据 需要删除 */
      // {
      //   id: '868221047652659',
      //   latitude: '32.409080',
      //   longitude: '119.420090',
      //   name: '868221047652659',
      //   iconPath: '../../images/on_marker.png',
      //   callout: {
      //     content: '编号868221047652659',
      //     padding: '8rpx',
      //     borderRadius: 5,
      //     borderWidth: 1,
      //     borderColor: "#000000",
      //     bgColor: "#c9c9c9"
      //   }
      // }
    ],
    address:'',
    is_show_tips:true,
    cur_mode_array: ['手动', '自动'],
    /**模式默认的值 默认是手动 */
    cur_mode_index: 0,
    cur_mode_item: '手动',
    cur_operator: ['合上', '断开'],
    /**状态默认值  默认是合上*/
    cur_operator_index: 0,
    cur_operator_item: '合上',
   
    mode_disabled: false,
    switch_disabled: false,
    // turnon_disabled: false,
    // turnoff_disabled: false,
    cur_onLine:false,
    cur_status:'',
    devices_str:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {    
    let that = this;  
 
    that.disLoad();
    that.load('请稍等...');

    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        var latitude = res.latitude;
        var longitude = res.longitude;

        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          default_latitude: res.latitude,
          default_longitude: res.longitude
        });
      }
    });  

    //首先请求 一次 设备列表和设备信息
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    };
    wx.request({
      url: "https://119.3.46.145/server/FindDevice?userid=" + app.globalData.userid,
      type: "post",
      header: header,
      success: res => {
        //如果没有设备 则return
        if(res.data == ''){
          wx.showModal({
            title: '提示',
            content: '当前用户还没有添加设备',
          });
          return;
        }       

        let devices_data = JSON.parse(res.data.devices);

        if (devices_data.length != 0) {
          app.globalData.dev_list = JSON.parse(res.data.devices);

          //把设备列表，组织称 markers列表 这一步markers内容比较少 [{devNo:'', description:''},{}]
          let local_markers = [];

          app.globalData.dev_list.forEach(function (item, index) {
            let tmp_json = {};
            tmp_json.id = item.devNo;
            tmp_json.name = item.description;
            tmp_json.groupId = item.groupId;
            local_markers.push(tmp_json);
          });

          app.globalData.markers = local_markers;

          let devices_arr = [];

          devices_data.forEach(function (item, index, self) {
            devices_arr.push(item.devNo);
          });

          let devices_str = devices_arr.join(',');

          that.setData({
            devices_str: devices_str
          });

          //请求到设备列表，第一次订阅设备
          //that.sendRegisterDevice(devices_str);
          wx.request({
            url: "https://119.3.46.145/server/GetLastInfo?devNo=" + devices_str,
            type: "post",
            header: header,
            success: res => {
              //加载隐藏
              // wx.hideToast();
              that.disLoad();
             

              let message = JSON.parse(res.data.data);
              //console.log(message);


              message.forEach(function (item, index, self) {
                //放进个数组，以备将来用来发送消息，判断是否成功使用
                that.checkDevice(item);

                //开始组织数据
                let data_json = item;
                //console.log(app.globalData.dev_list, "dev_list global");       

                let tmp_dev_config = {
                  secondTurnOffTime: data_json.SecondTurnOffTime,
                  devNo: data_json.devNo,
                  latitude: data_json.Latitude == 0 ? that.data.default_latitude : data_json.Latitude,
                  type: data_json.type,
                  firstTurnOnTime: data_json.FirstTurnOnTime,
                  devCurrentTime: data_json.DevCurrentTime,
                  longitude: data_json.Longitude == 0 ? that.data.default_longitude : data_json.Longitude,
                  firstOrSumElec: data_json.FirstOrSumElec,  //第一路电流或者总电流 单位毫安
                  secondTurnOnTime: data_json.SecondTurnOnTime,
                  auto: data_json.Auto,
                  onLine: data_json.OnLine,
                  secondElec: data_json.SecondElec, //第二路电流（预留）
                  firstSwitch: data_json.FirstSwitch,  //第一路开关
                  firstTurnOffTime: data_json.FirstTurnOffTime,
                  secondSwitch: data_json.SecondSwitch,  //第二路开关
                  description: ''
                };

                //把description信息补上
                app.globalData.dev_list.forEach(function (tmp_item, tmp_index, tmp_self) {
                  if (tmp_item.devNo == data_json.devNo) {
                    tmp_dev_config.description = tmp_item.description;
                    return false;
                  }
                });

                //开始构造所有设备的配置数组that.data.dev_list_detail [{},{},{}]
                //策略是 遍历全局变量 app.global.dev_list [{devNo:'',groupId:'', description:''}]  遍历里面的每一项 每一项的devNo和message传过来的数据devNo比对，如果，没有，则添加//到that.data.dev_list_detail，否则只是改变that.data.dev_list_detail的配置

                let is_have = false; //判断设备数组到底包不包含当前设备 如果包含 is_have 置为 true只是重新跟新一下 配置数据 如果没有，循环结束后需要//添加设备配置

                //遍历dev_list_detail 修改对应devNo的配置
                that.data.dev_list_detail.forEach(function (_item, _index) {
                  if (_item.devNo == data_json.devNo) {
                    //如果本页变量 dev_list_detail 设备配置数组的devNo == 全局变量设备列表的数组的devNo 修改配置值
                    is_have = true;

                    let param = {};
                    let string = "dev_list_detail[" + _index + "]";
                    param[string] = tmp_dev_config;
                    that.setData(param);

                    //退出 修改配置值
                    return false
                  }
                });


                if (is_have == false) {
                  let dev_list_detail_copy = that.data.dev_list_detail;
                  dev_list_detail_copy.push(tmp_dev_config);
                  that.setData({
                    dev_list_detail: dev_list_detail_copy
                  });
                }
              });

              //根据获得的实时信息，组织marker
              let tmp_marker = [];

              that.data.dev_list_detail.forEach(function (r_item, r_index, r_self) {
                let tmp_item = {
                  id: r_item.devNo,
                  latitude: r_item.latitude,
                  longitude: r_item.longitude,
                  name: r_item.devNo,
                  callout: {
                    content: '',
                    padding: '8rpx',
                    borderRadius: 5,
                    borderWidth: 1,
                    borderColor: "#000000",
                    bgColor: "#c9c9c9"
                  }
                }

                let callout_str = '';

                callout_str += '名称：' + r_item.description + '\r\n';
                callout_str += '编号：' + r_item.devNo + '\r\n';
                callout_str += '经度：' + r_item.longitude + '\r\n';
                callout_str += '纬度：' + r_item.latitude + '\r\n';

                if (r_item.onLine === false) {
                  tmp_item.iconPath = '../../images/off_line.png';
                  callout_str += "当前状态：离线\r\n"
                }

                if (r_item.onLine === true) {
                  if (r_item.firstSwitch === true) {
                    tmp_item.iconPath = '../../images/on_marker.png';
                    callout_str += "当前状态：在线 已连接\r\n";
                  }

                  if (r_item.firstSwitch === false) {
                    tmp_item.iconPath = '../../images/off_marker.png';
                    callout_str += "当前状态： 在线 已断开\r\n";
                  }
                }

                tmp_item.callout.content = callout_str;

                tmp_marker.push(tmp_item);
              });

              that.setData({
                markers: tmp_marker
              });

              app.globalData.markers = that.data.markers;

              //markers至少存在一个点 并且 设置中心和设置缩放比值缩放一次               
              if (that.data.markers.length >= 1 && that.data.is_load_center_scale == false) {
                //设置中心点  
                that.getMapCenter();

                //设置缩放比
                that.getMapScale();

                that.setData({
                  is_load_center_scale: true
                });
              }
             
            },
            fail: error => {
              wx.showModal({
                title: '提示',
                content: '请求实时信息出错' + res
              })
            }
          })
        }
        else {
          //当前无设备 ，设置地图的经纬度为当前位置
          wx.getLocation({
            type: 'wgs84',
            success: function (res) {
              var latitude = res.latitude;
              var longitude = res.longitude;

              that.setData({
                latitude: res.latitude,
                longitude: res.longitude
              });
            }
          })
        }

      },
      fail: function (res) {
        // wx.hideToast();//加载隐藏
        that.disLoad();
        wx.showModal({
          title: '提示',
          content: '请求设备列表出错' + res
        })
      }
    });


    that.refreshPage();
  },

  onPointTap:function(e){   
    let that = this;  

    that.setData({
      is_show_tips:false
    });
  
    //let marker_id = parseInt(e.markerId)-1;   
    let marker_id = e.markerId;
    //let marker = that.data.markers[marker_id]; 
    let marker = {};
 
    that.data.markers.forEach(function(item, index){
      if(item.id == marker_id){
        marker = item;
        return false;
      }
    });

    if (marker.iconPath == "../../images/off_marker.png"){
      that.setData({
        tap_control_stauts:"在线 关闭"
      });
    }

    if (marker.iconPath == "../../images/off_line.png") {
      that.setData({
        tap_control_stauts: "不在线"
      });
    }

    if (marker.iconPath == "../../images/on_marker.png") {
      that.setData({
        tap_control_stauts: "在线 合上"
      });
    }

    let tmp_current = {};    
    that.data.dev_list_detail.forEach(function(_item, _index){
      if(_item.devNo == marker_id){
        tmp_current = _item;
        return false;
      }
    });   

    

    //逆解析城市
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: marker.latitude,
        longitude: marker.longitude
      },
      success: function (res) {
        //获取当前地址成功
        // console.log(res, "res 逆解析");
        // let markers_arr = that.data.markers;
       
        // markers_arr.forEach(function(item, index, self){
        //   console.log(item.callout, "item");
        //   if (item.id == marker_id){
        //     item.callout.content += "地址:\r\n";
        //     item.callout.content += res.result.address
        //     return false;
        //   }
        // });


        that.setData({
          address: res.result.address,
          // markers: markers_arr
        });
      },
      fail: function (res) {
        console.log('获取当前地址失败');
      }
    });     

    that.setData({
      tap_control_longtitude: marker.longitude,
      tap_control_latitude: marker.latitude,
      current_info: tmp_current,
      detail_is_show:true
    });

    /**['手动', '自动']*/
    if (that.data.current_info.auto == true) {
      that.setData({
        cur_mode_index: 1,
        cur_mode_item: "自动"
        //cur_operator_index: 0,        
      });
    }

    /**['合上','断开'], */
    if (that.data.current_info.onLine == false) {
      that.setData({
        cur_operator_index: 1,
        cur_operator_item: "断开"
      });
    }

    if (that.data.current_info.onLine == false) {
      that.setData({
        mode_disabled: true,
        switch_disabled: true,
        // turnon_disabled: true,
        // turnoff_disabled: true
      });     
    }

    if (that.data.current_info.onLine == true) {
      that.setData({
        cur_onLine:true
      });
    }

    if(that.data.current_info.onLine == false){
      that.setData({
        cur_status:'离线'
      });
    }
    else{
      if(that.data.current_info.firstSwitch == true){
        that.setData({
          cur_status: '在线 已合上'
        });
      }

      if (that.data.current_info.firstSwitch == false) {
        that.setData({
          cur_status: '在线 已断开'
        });
      }
    }

    // if (that.data.current_info.onLine == false) {
    //   wx.showModal({
    //     title: '提示',
    //     content: '离线设备只能设置经纬度',
    //   })
    // }
  },

  //点击右上角按钮 回到中心点 回到计算出来的scale
  coverImageTocenter:function(){
    // 中心点
    let that = this;
    var mapCtx = wx.createMapContext('myMap');   
    that.setData({
      mapCtx: mapCtx
    });

    mapCtx.moveToLocation({
      latitude:that.data.latitude,
      longitude:that.data.longitude,
      success(res) {      
        
      }
    });

    let tmp_scale = that.data.scale;
    that.setData({
      scale:tmp_scale
    });
  },

  isOpen: function (e) {
    var that = this;
    var idx = e.currentTarget.dataset.index;

    var dev_list = that.data.coverview_dev_list;

    // var curId = 0;
    dev_list.forEach(function (item, index, self) {
      if (idx == item.id) {
        if (item.hidden == true && item.down == "/images/icon_down2x.png") {
          item.down = "/images/icon_up2x.png";
        } else {
          item.down = "/images/icon_down2x.png";
        }
        item.hidden = !item.hidden;
        // curId = i;
      } else {
        item.hidden = true;
        item.down = "/images/icon_down2x.png";
      }
    });
    // }
    that.setData({
      coverview_dev_list: dev_list
    });
  },

  //单击右上角列表图标数显列表 点击列表可以调到指定的marker
  coverImageList:function(){
    let that = this;

    let tmp_show_coverview_list = that.data.show_coverview_list;

    that.setData({
      show_coverview_list: !tmp_show_coverview_list
    });    

    if (!tmp_show_coverview_list == true){
      //展示列表
    }
    if (!tmp_show_coverview_list == false){
      //影藏设备列表   
      return;
    }
   
    var header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    };

    wx.request({
      url: 'https://119.3.46.145/server/FindGroup?userid=' + app.globalData.userid,
      method: 'POST',
      header: header,
      success: res => {
        let groups = JSON.parse(res.data.data);
        wx.request({
          url: 'https://119.3.46.145/server/FindDevice?userid=' + app.globalData.userid,
          method: 'POST',
          header: header,
          success: res => {
            // console.log(res, "res");
            // console.log(res.data, "res.data");
            // console.log(res.data.devices, "res.data.devices");

            let devices = JSON.parse(res.data.devices);
            let devCache = [];

            let points = [];
            for (let i in devices) {
              let dev = devices[i];
              let groupname = "";
              for (let j = 0; j < groups.length; j++) {
                if (groups[j].groupId == dev.groupId) {
                  groupname = groups[j].groupName;
                  break;
                }
              }

              devCache[dev.devNo] = {
                name: dev.description,
                groupId: dev.groupId
              };

              let is_onLine = false;
              let is_firstSwitch = false;
              let longitude ='';
              let latitude = '';

              that.data.dev_list_detail.forEach(function (item, index, self) {
                if (item.devNo == dev.devNo) {
                  is_onLine = item.onLine;
                  is_firstSwitch = item.firstSwitch;
                  longitude = item.longitude;
                  latitude = item.latitude;
                  return false;
                }
              });

              let hasclass = false;
              for (let p in points) {
                let item = points[p];
                if (item.id === dev.groupId) {
                  let childpoints = item.points; 
                  childpoints.push({
                    devNo: dev.devNo,
                    devName: dev.description,
                    onLine:is_onLine,
                    firstSwitch:is_firstSwitch,
                    longitude: longitude,
                    latitude:latitude
                  });
                  hasclass = true;
                }
              }

              if (!hasclass) {
                points.push({
                  name: groupname,
                  id: dev.groupId,
                  hidden: true,
                  images: '/images/group.png',
                  down: '/images/icon_down2x.png',
                  points: [
                    {
                      devNo: dev.devNo,
                      devName: dev.description,
                      onLine: is_onLine,
                      firstSwitch: is_firstSwitch,
                      longitude: longitude,
                      latitude:latitude
                    }
                  ]
                })
              }
            }

            that.setData({
              coverview_dev_list: points
            });
          },
          fail: function (error) {
            console.log(error, "FindDevice error");
          }
        })
      },
      fail: function (error) {
        console.log(error, "FindDevice error");
      }
    });
  },

  goto_map_marker:function(info){   
    let that = this;

    that.setData({
      show_coverview_list: false
    });
    let current_info = info.currentTarget.dataset.info;
  
    var mapCtx = wx.createMapContext('myMap');

    if (current_info.latitude == undefined || current_info.longitude == undefined){
      wx.showModal({
        title: '提示',
        content: '当前地图上暂无该设备点！',
      })
      return;
    }

    mapCtx.moveToLocation({
      latitude: current_info.latitude,
      longitude: current_info.longitude,
      success(res) {
        console.log("转到指定的marker");
      }
    });

    // that.setData({
    //   show_coverview_list:false
    // });
  },

  sendRegisterDevice:function(devices_str){
    let that = this;

    var header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    };

    wx.request({
      url: 'https://119.3.46.145/server/RegisterDevice?devNo=' + devices_str,
      header: header,
      success: res => {
        //console.log(res);
      },
      fail: function (err) {

      }
    });


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this;
    //that.mapCtx = wx.createMapContext('myMap');
    //以下是作为调试方便而暂时屏蔽的 不能删除
    // wx.showModal({
    //   title: '提示',
    //   content: '请先登录',
    //   success(res) {
    //     if (res.confirm) {
    //       wx.navigateTo({
    //         url: '../login/login',
    //       })
    //     } else if (res.cancel) {
          
    //     }
    //   }
    // })    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {    
    let that = this;
  },

  refreshPage:function(){
    let that = this;  
    // var count = 0;

    /**  服务器出问题了，暂时屏蔽这段 需要恢复 不能删除*/
    timer = setInterval(function () {     
      that.refreshPointsList();   
      // count++;  
      //if(count%5 == 0){
        //每100秒注册一次设备，10分钟未注册，取消订阅，节省次数
        //that.sendRegisterDevice(that.data.devices_str);       
      //} 
    }, 20 * 1000);  
  },

//循环的函数需要做的是查询设备名，在查询设备实时信息
refreshPointsList:function(){
  let that = this;
  let header = {
    'content-type': 'application/x-www-form-urlencoded',
    'cookie': "openid=" + app.globalData.openid
  };

  let devices_data = app.globalData.dev_list;

  if (devices_data.length != 0) {
    //把设备列表，组织称 markers列表 这一步markers内容比较少 [{devNo:'', description:''},{}]
    let local_markers = [];

    app.globalData.dev_list.forEach(function (item, index) {
      let tmp_json = {};
      tmp_json.id = item.devNo;
      tmp_json.name = item.description;
      tmp_json.groupId = item.groupId;
      local_markers.push(tmp_json);
    });

    app.globalData.markers = local_markers;

    let devices_arr = [];

    devices_data.forEach(function (item, index, self) {
      devices_arr.push(item.devNo);
    });

    let devices_str = devices_arr.join(',');

    that.setData({
      devices_str: devices_str
    });

    //请求到设备列表，第一次订阅设备
    //that.sendRegisterDevice(devices_str);

    wx.request({
      url: "https://119.3.46.145/server/GetLastInfo?devNo=" + devices_str,
      type: "post",
      header: header,
      success: res => {
        //加载隐藏
        // wx.hideToast();
        that.disLoad();

        let message = JSON.parse(res.data.data);
        //console.log(message);

        message.forEach(function (item, index, self) {
          //放进个数组，以备将来用来发送消息，判断是否成功使用
          that.checkDevice(item);

          //开始组织数据
          let data_json = item;
          //console.log(app.globalData.dev_list, "dev_list global");       

          let tmp_dev_config = {
            secondTurnOffTime: data_json.SecondTurnOffTime,
            devNo: data_json.devNo,
            latitude: data_json.Latitude == 0 ? that.data.default_latitude : data_json.Latitude,
            type: data_json.type,
            firstTurnOnTime: data_json.FirstTurnOnTime,
            devCurrentTime: data_json.DevCurrentTime,
            longitude: data_json.Longitude == 0 ? that.data.default_longitude : data_json.Longitude,
            firstOrSumElec: data_json.FirstOrSumElec,  //第一路电流或者总电流 单位毫安
            secondTurnOnTime: data_json.SecondTurnOnTime,
            auto: data_json.Auto,
            onLine: data_json.OnLine,
            secondElec: data_json.SecondElec, //第二路电流（预留）
            firstSwitch: data_json.FirstSwitch,  //第一路开关
            firstTurnOffTime: data_json.FirstTurnOffTime,
            secondSwitch: data_json.SecondSwitch,  //第二路开关
            description: ''
          };

          //把description信息补上
          app.globalData.dev_list.forEach(function (tmp_item, tmp_index, tmp_self) {
            if (tmp_item.devNo == data_json.devNo) {
              tmp_dev_config.description = tmp_item.description;
              return false;
            }
          });

          //开始构造所有设备的配置数组that.data.dev_list_detail [{},{},{}]
          //策略是 遍历全局变量 app.global.dev_list [{devNo:'',groupId:'', description:''}]  遍历里面的每一项 每一项的devNo和message传过来的数据devNo比对，如果，没有，则添加//到that.data.dev_list_detail，否则只是改变that.data.dev_list_detail的配置

          let is_have = false; //判断设备数组到底包不包含当前设备 如果包含 is_have 置为 true只是重新跟新一下 配置数据 如果没有，循环结束后需要//添加设备配置

          //遍历dev_list_detail 修改对应devNo的配置
          that.data.dev_list_detail.forEach(function (_item, _index) {
            if (_item.devNo == data_json.devNo) {
              //如果本页变量 dev_list_detail 设备配置数组的devNo == 全局变量设备列表的数组的devNo 修改配置值
              is_have = true;

              let param = {};
              let string = "dev_list_detail[" + _index + "]";
              param[string] = tmp_dev_config;
              that.setData(param);

              //退出 修改配置值
              return false
            }
          });


          if (is_have == false) {
            let dev_list_detail_copy = that.data.dev_list_detail;
            dev_list_detail_copy.push(tmp_dev_config);
            that.setData({
              dev_list_detail: dev_list_detail_copy
            });
          }
        });

        //根据获得的实时信息，组织marker
        let tmp_marker = [];

        that.data.dev_list_detail.forEach(function (r_item, r_index, r_self) {
          let tmp_item = {
            id: r_item.devNo,
            latitude: r_item.latitude,
            longitude: r_item.longitude,
            name: r_item.devNo,
            callout: {
              content: '',
              padding: '8rpx',
              borderRadius: 5,
              borderWidth: 1,
              borderColor: "#000000",
              bgColor: "#c9c9c9"
            }
          }

          let callout_str = '';

          callout_str += '名称：' + r_item.description + '\r\n';
          callout_str += '编号：' + r_item.devNo + '\r\n';
          callout_str += '经度：' + r_item.longitude + '\r\n';
          callout_str += '纬度：' + r_item.latitude + '\r\n';

          if (r_item.onLine === false) {
            tmp_item.iconPath = '../../images/off_line.png';
            callout_str += "当前状态：离线\r\n"
          }

          if (r_item.onLine === true) {
            if (r_item.firstSwitch === true) {
              tmp_item.iconPath = '../../images/on_marker.png';
              callout_str += "当前状态：在线 已连接\r\n";
            }

            if (r_item.firstSwitch === false) {
              tmp_item.iconPath = '../../images/off_marker.png';
              callout_str += "当前状态： 在线 已断开\r\n";
            }
          }

          tmp_item.callout.content = callout_str;

          tmp_marker.push(tmp_item);
        });

        that.setData({
          markers: tmp_marker
        });

        app.globalData.markers = that.data.markers;



        //markers至少存在一个点 并且 设置中心和设置缩放比值缩放一次
        //  && that.data.is_load_center_scale == false
        if (that.data.markers.length >= 1 && that.data.is_load_center_scale == false) {
          //设置中心点  
          that.getMapCenter();

          //设置缩放比
          that.getMapScale();

          that.setData({
            is_load_center_scale: true
          });
        }

       //设备增删改过，都要设置中心和设置缩放比值缩放一次
        if (app.globalData.edit_del_add_dev_flag == true){
          //设置中心点  
          that.getMapCenter();

          //设置缩放比
          that.getMapScale();

          app.globalData.edit_del_add_dev_flag = false;
        }
      },
      fail: error => {
        wx.showModal({
          title: '提示',
          content: '请求实时信息出错' + res
        })
      }
    })
  }
  else {
    //当前无设备 ，设置地图的经纬度为当前位置
      wx.getLocation({
        type: 'wgs84',
        success: function (res) {
          var latitude = res.latitude;
          var longitude = res.longitude;

          that.setData({
            latitude: res.latitude,
            longitude: res.longitude
          });
        }
      });
    } 
  },

  checkDevice:function(obj)
  {
    let devNo = obj.devNo;
    let state = 0;
    //记录下最新返回的状态
    //deviceInfoList[devNo] = obj;

    //检查是否在线
    let online = obj.OnLine;
    if(online) {
      state = 1;
      //判断在线列表中是否存在该设备，不在添加
      if (app.globalData.onlineDevice.indexOf(devNo) === -1) {
        app.globalData.onlineDevice.push(devNo);
      }
      //判断不在线列表是否存在该设备,在就删除
      if (app.globalData.offlineDevice.indexOf(devNo) !== -1) {
        app.globalData.offlineDevice.splice(app.globalData.offlineDevice.indexOf(devNo), 1);
      }
    }
    else{
      state = 0;
      //和在线相反
      if (app.globalData.offlineDevice.indexOf(devNo) === -1) {
        app.globalData.offlineDevice.push(devNo);
      }
      if (app.globalData.onlineDevice.indexOf(devNo) !== -1) {
        app.globalData.onlineDevice.splice(app.globalData.onlineDevice.indexOf(devNo), 1);
      }
    }

  //是否为自动模式
  let auto = obj.Auto;
  if (auto) {
    if (app.globalData.autoDevice.indexOf(devNo) === -1) {
      app.globalData.autoDevice.push(devNo);
    }
    if (app.globalData.manualDevice.indexOf(devNo) !== -1) {
      app.globalData.manualDevice.splice(app.globalData.manualDevice.indexOf(devNo), 1);
    }
  }
  else {
    if (app.globalData.manualDevice.indexOf(devNo) === -1) {
      app.globalData.manualDevice.push(devNo);
    }
    if (app.globalData.autoDevice.indexOf(devNo) !== -1) {
      app.globalData.autoDevice.splice(app.globalData.autoDevice.indexOf(devNo), 1);
    }
  }

  //检查设备开关状态
  let switch_state = obj.FirstSwitch;
  if (switch_state) {
    if (state > 0)
      state = 2;
    if (app.globalData.turnOnDevice.indexOf(devNo) === -1) {
      app.globalData.turnOnDevice.push(devNo);
    }
    if (app.globalData.turnOffDevice.indexOf(devNo) !== -1) {
      app.globalData.turnOffDevice.splice(app.globalData.turnOffDevice.indexOf(devNo), 1);
    }
  }
  else {
    if (state > 0)
      state = 1;
    if (app.globalData.turnOffDevice.indexOf(devNo) === -1) {
      app.globalData.turnOffDevice.push(devNo);
    }
    if (app.globalData.turnOnDevice.indexOf(devNo) !== -1) {
      app.globalData.turnOnDevice.splice(app.globalData.turnOnDevice.indexOf(devNo), 1);
    }
  }
},


connect:function(e){
  let that = this;
  let devNo = e.currentTarget.dataset.devid;
 
  if (app.globalData.onlineDevice.indexOf(devNo) === -1) {  
    wx.showModal({
      title: '提示',
      content: '设备离线状态,无法发送指令到设备',
    })
    return;
  }

  if (app.globalData.turnOffDevice.indexOf(devNo) !== -1 && app.globalData.turnOnDevice.indexOf(devNo) === -1) {
    //合上开关
    that.turnOn(devNo);
    // info.close();
  } else {
    //alert("开关已合上 " + no);
    wx.showModal({
      title: '提示',
      content: '开关已合上'+devNo,
    });
    
  }
},

disconnect:function(e){
  let devNo = e.currentTarget.dataset.devid;
  let that = this;
 
  if (app.globalData.onlineDevice.indexOf(devNo) === -1) {  
    wx.showModal({
      title: '提示',
      content: '设备离线状态,无法发送指令到设备',
    })
    return;
  }

  if (app.globalData.turnOffDevice.indexOf(devNo) === -1 && app.globalData.turnOnDevice.indexOf(devNo) !== -1) {
    //断开开关
    that.turnOff(devNo);
    // info.close();
  } else {
    wx.showModal({
      title: '提示',
      content: "开关已断开 " + devNo,
    })
  }
},


//切换模式 
change_mode:function(e){
  //true 自动 false 手动
  let that = this;
  let cur_mode = e.currentTarget.dataset.mode;
  let devNo = e.currentTarget.dataset.devid;

  if (app.globalData.onlineDevice.indexOf(devNo) === -1) {
    wx.showModal({
      title: '提示',
      content: '当前设备不在线，操作失败',
    });
    return;
  }

 /**切换就需要取反 !cur_mode==false表示当前是自动 切换后成为手动; !cur_mode==true表示当前是手动 切换后成为自动;*/

  if (app.globalData.autoDevice.indexOf(devNo) !== -1) {
    //切换到手动模式
    that.setManual(devNo);
  }  
  
  if (app.globalData.manualDevice.indexOf(devNo) !== -1) {
    //切换到自动模式
    that.setAuto(devNo);
  }
},

turnOn:function(devNo)
{
  let that = this;
  that.disLoad();
  that.load("正在操作请稍等");

  if(app.globalData.onlineDevice.indexOf(devNo) === -1)
  {
    // $.messager.alert("提示", '当前设备不在线，操作失败');
    wx.showModal({
      title: '提示',
      content: '当前设备不在线，操作失败'
    })
    that.disLoad();
    return;
  }


  wx.request({
    url: 'https://119.3.46.145/server/m_set_dev_on?devId=' + devNo,
    method: 'POST',
    header: var_header,
    success: res => {
      setTimeout(function () {
        if (app.globalData.turnOnDevice.indexOf(devNo) === -1) {
          try_times++;
          if (try_times <= retimes) {
            that.turnOn(devNo);
          }
          else {
            try_times = 0;           
            wx.showModal({
              title: '提示',
              content: '操作失败',
            });
            that.disLoad();
          }
        }
        else {        
          wx.showModal({
            title: '提示',
            content: '操作成功'
          });
          that.disLoad();

          let tmp_current_info = that.data.current_info;
          tmp_current_info.firstSwitch = true;

          let tmp_markers = that.data.markers;
          
          tmp_markers.forEach(function(item, index, self){
            if(item.devNo == devNo){
              item.iconPath = "../../images/on_marker.png";
              return false;  
            }
          });

          let tmp_cur_status = that.data.cur_status;

          if(that.data.current_info.onLine == true){
            tmp_cur_status = "在线 已合上";
          }

          if (that.data.current_info.onLine == false) {
            tmp_cur_status = "离线";
          }          

          that.setData({
            current_info: tmp_current_info,
            markers: tmp_markers,
            cur_status: tmp_cur_status
          });
        }
      }, reInterval);
    },
    fail: function (error) {
      console.log(error, "FindDevice error");
    }
  });
},


turnOff:function(devNo) {
  let that = this;
  that.disLoad();
  that.load("正在操作，请等待！");

  if (app.globalData.onlineDevice.indexOf(devNo) === -1) {
    // $.messager.alert("提示", '当前设备不在线，操作失败');
    wx.showModal({
      title: '提示',
      content: '当前设备不在线，操作失败'
    })
    that.disLoad();
    return;
  }

  wx.request({
    url: 'https://119.3.46.145/server/m_set_dev_off?devId=' + devNo,
    method: 'POST',
    header: var_header,
    success: res => {
      setTimeout(function () {
        if (app.globalData.turnOffDevice.indexOf(devNo) === -1) {
          try_times++;
          if (try_times <= retimes) {
            that.turnOff(devNo);
          }
          else {
            try_times = 0;
            // alert("操作失败");
            wx.showModal({
              title: '提示',
              content: '操作失败',
            })
            that.disLoad();
          }
        }
        else {
          // alert("操作成功");
          wx.showModal({
            title: '提示',
            content: '操作成功'
          })
          that.disLoad();

          let tmp_current_info = that.data.current_info;
          tmp_current_info.firstSwitch = false;

          let tmp_markers = that.data.markers;

          tmp_markers.forEach(function (item, index, self) {
            if (item.devNo == devNo) {
              item.iconPath = "../../images/off_marker.png";
              return false;
            }
          });



          let tmp_cur_status = that.data.cur_status;

          if (that.data.current_info.onLine == true) {
            tmp_cur_status = "在线 已断开";
          }

          if (that.data.current_info.onLine == false) {
            tmp_cur_status = "离线";
          }


          that.setData({
            current_info: tmp_current_info,
            markers: tmp_markers,
            cur_status: tmp_cur_status
          });
        }
      }, reInterval);
    },
    fail: function (error) {
      console.log(error, "FindDevice error");
    }
  });
},

setAuto:function(devNo) {
  let that = this;
  that.disLoad();
  that.load("正在操作，请等待！");

  if (app.globalData.onlineDevice.indexOf(devNo) === -1) {
    wx.showModal({
      title: '提示',
      content: '当前设备不在线，操作失败',
    })
    
    that.disLoad();
    return;
  }

  wx.request({
    url: 'https://119.3.46.145/server/m_set_dev_auto?devId=' + devNo,
    method: 'POST',
    header: var_header,
    success: res => {     
      setTimeout(function () {
        if (app.globalData.autoDevice.indexOf(devNo) === -1) {
          try_times++;
          if (try_times <= retimes) {
            that.setAuto(devNo);
          }
          else {
            try_times = 0;
            wx.showModal({
              title: '提示',
              content: '操作失败',
            });
            that.disLoad();
          }
        }
        else {
          wx.showModal({
            title: '提示',
            content: '操作成功',
          });
          that.disLoad();
          //改变页面值
          let tmp_current_info = that.data.current_info;
          tmp_current_info.auto = true;

          that.setData({
            current_info: tmp_current_info
          });
        }
      }, reInterval);
    },
    fail: function (error) {
      console.log(error, "setManual error");
    }
  });

  // $.ajax({
  //   url: "/server/m_set_dev_auto",
  //   data: {
  //     devId: devNo
  //   },
  //   type: 'POST',
  //   success: function () {
  //     setTimeout(function () {
  //       if (autoDevice.indexOf(devNo) === -1) {
  //         try_times++;
  //         if (try_times <= retimes) {
  //           SetAuto(devNo);
  //         }
  //         else {
  //           try_times = 0;
  //           alert("操作失败");
  //           disLoad();
  //         }
  //       }
  //       else {
  //         alert("操作成功");
  //         disLoad();
  //       }
  //     }, reInterval);
  //   }
  // });
},

setManual:function(devNo) {
  let that = this; 
  that.disLoad();
  that.load("正在操作，请等待！");

  if (app.globalData.onlineDevice.indexOf(devNo) === -1) {   
    wx.showModal({
      title: '提示',
      content: '当前设备不在线，操作失败'
    })
    that.disLoad();
    return;
  }

  wx.request({
    url: 'https://119.3.46.145/server/m_set_dev_manual?devId=' + devNo,
    method: 'POST',
    header: var_header,
    success: res => {
      // let groups = JSON.parse(res.data.data);
      setTimeout(function () {
        if (app.globalData.manualDevice.indexOf(devNo) === -1) {
          try_times++;
          if (try_times <= retimes) {
            that.setManual(devNo);
          }
          else {
            try_times = 0;
            wx.showModal({
              title: '提示',
              content: '操作失败'
            });
           
            that.disLoad();
          }
        }
        else {
          wx.showModal({
            title: '提示',
            content: '操作成功'
          });
          that.disLoad();

          //改变页面值
          let tmp_current_info = that.data.current_info;
          tmp_current_info.auto = false;

          that.setData({
            current_info: tmp_current_info
          });
        }
      }, reInterval);
    },
    fail: function (error) {
      console.log(error, "setManual error");
    }
  });
},

//小程序提供的获取当前页中心点的方法
  mapchangeTap: function () {  
    // 中心点
    let that = this;

    let mapCtx = wx.createMapContext('myMap');
    that.setData({
      mapCtx: mapCtx
    }); 

    mapCtx.getCenterLocation({
      // success(res) {      
      //   const latitude = res.latitude;
      //   const longitude = res.longitude;
      // }
    });
  },

//设置中心点
  getMapCenter:function(){   
    let that = this;
    let pos_arr = that.data.markers;
    let total = pos_arr.length;
    let X = 0, Y = 0, Z = 0;
    pos_arr.forEach(function (item, index) {
      //console.log(item); //这里的item就是从数组里拿出来的每一个每一组     
      let lat, lon, x, y, z;      
      lat = item.latitude * Math.PI / 180;
      lon = item.longitude * Math.PI / 180;
      x = Math.cos(lat) * Math.cos(lon);
      y = Math.cos(lat) * Math.sin(lon);
      z = Math.sin(lat);
      X += x;
      Y += y;
      Z += z;
    });


    X = X / total;
    Y = Y / total;
    Z = Z / total;
    let Lon = Math.atan2(Y, X);
    let Hyp = Math.sqrt(X * X + Y * Y);
    let Lat = Math.atan2(Z, Hyp);
    let center_latitude = Lat * 180 / Math.PI;
    let center_longitude = Lon * 180 / Math.PI;

    //console.log(center_latitude, "latitude center");
    //console.log(center_longitude, "longitude center");  
    that.setData({
      latitude: center_latitude,
      longitude: center_longitude
    });  
  },


//计算地图缩放比
  getMapScale:function(){
    let that = this;
    let pos_arr = that.data.markers; 
    let max_latitude = 0.0;
    let max_longitude = 0.0;
    let min_latitude = pos_arr[0].latitude;
    let min_longitude = pos_arr[0].longitude;

    pos_arr.forEach(function (item, index) { 

      if (item.longitude >= max_longitude) {
        max_longitude = item.longitude;
      }

      if (item.latitude >= max_latitude){
        max_latitude = item.latitude ;
      }

      if (item.longitude <= min_longitude){
        min_longitude = item.longitude;
      }

      if (item.latitude <= min_latitude) {
        min_latitude = item.latitude;
      }    
    });

    let distance = that.distance(max_latitude, max_longitude, min_latitude, min_longitude);
    //console.log(distance, "dis");

    var zoom = ["50", "100", "200", "500", "1000", "2000", "5000", "10000", "20000", "25000", "50000", "100000", "200000", "500000", "1000000", "3000000"]//级别18到3。 
    let scale = 3; 
    
    for (var i = 0, zoomLen = zoom.length; i < zoomLen; i++) {
      if (zoom[i] - distance > 0) {
        scale = 18 - i + 1;

        that.setData({
          scale: scale
        });

        //console.log(JSON.stringify(that.data))
        return scale;//之所以会多3，是因为地图范围常常是比例尺距离的10倍以上。所以级别会增加3。  
      }
      
      if (distance>3000000){
        that.setData({
          scale: 3
        });
      }
    }
  },

//计算地图上两点距离
  distance: function (la1, lo1, la2, lo2) {
    var La1 = la1 * Math.PI / 180.0;
    var La2 = la2 * Math.PI / 180.0;
    var La3 = La1 - La2;
    var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10;
    s = s.toFixed(2);
    return s;
  },

  //定位方法
  getUserLocation: function () {
    let that = this;
    wx.getSetting({
      success: (res) => {
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面  res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权  res.authSetting['scope.userLocation'] == true    表示 地理位置授权        
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          //未授权
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                //取消授权
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                //确定授权，通过wx.openSetting发起授权请求
                wx.openSetting({
                  success: function (res) {
                    if (res.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      that.geo();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //用户首次进入页面,调用wx.getLocation的API
          that.geo();
        }
        else {
          //console.log('授权成功')
          //调用wx.getLocation的API
          that.geo();
        }
      }
    })
  },

  // 获取定位城市
  geo: function () {
    let that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        var latitude = res.latitude;
        var longitude = res.longitude;

        var speed = res.speed;
        var accuracy = res.accuracy;       
      }
    })
  },  

  goTodetail:function(){
    let that = this;
    wx.navigateTo({
      url: '../detail/detail?current_info='+JSON.stringify(that.data.current_info)+"&address="+that.data.address
    })
  },

  load:function(s){
    wx.showLoading({
      title: s,
    });
  },

  disLoad:function(){
    wx.hideLoading();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    let that = this;
    that.setData({
      dev_list_detail:[],
      is_load_center_scale: false,
      markers:[]
    });

    app.globalData.markers = [];
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let that = this;
    // let wxst = that.data.wxst;
    // wxst.close(res => {
    //   console.info('连接关闭');
    // }); 

    clearInterval(timer);


  },

  moveToLocation:function(){
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  getCenter:function(){
    // let that = this;
    // let points = that.data.markers;
    // if (points.length > 0) {
    //   var maxLng = points[0].longitude;
    //   var minLng = points[0].longitude;
    //   var maxLat = points[0].latitude;
    //   var minLat = points[0].latitude;
    //   var res;
    //   for (var i = points.length - 1; i >= 0; i--) {
    //     res = points[i];
    //     if (res.longitude > maxLng) maxLng = res.longitude;
    //     if (res.longitude < minLng) minLng = res.longitude;
    //     if (res.latitude > maxLat) maxLat = res.latitude;
    //     if (res.latitude < minLat) minLat = res.latitude;
    //   };
    //   var cenLng = (parseFloat(maxLng) + parseFloat(minLng)) / 2;
    //   var cenLat = (parseFloat(maxLat) + parseFloat(minLat)) / 2;

    //   that.setData({       
    //     longitude: cenLng,
    //     latitude: cenLat
    //   });

      
      // zoom = that.getZoom(maxLng, minLng, maxLat, minLat);
      //map.centerAndZoom(new BMap.Point(cenLng, cenLat), zoom);
    // } else {
      //没有坐标，显示全中国  
      //map.centerAndZoom(new BMap.Point(103.388611, 35.563611), 5);
    // }
  },

  getZoom:function(maxLng, minLng, maxLat, minLat) {
    var zoom = ["50", "100", "200", "500", "1000", "2000", "5000", "10000", "20000", "25000", "50000", "100000", "200000", "500000", "1000000", "2000000"]//级别18到3。  
    var pointA = new BMap.Point(maxLng, maxLat);  // 创建点坐标A  
    var pointB = new BMap.Point(minLng, minLat);  // 创建点坐标B  
    var distance = map.getDistance(pointA, pointB).toFixed(1);  //获取两点距离,保留小数点后两位  
    for (var i = 0, zoomLen = zoom.length; i < zoomLen; i++) {
      if (zoom[i] - distance > 0) {
        return 18 - i + 3;//之所以会多3，是因为地图范围常常是比例尺距离的10倍以上。所以级别会增加3。  
      }
    };
  }
})